// 运行时配置
import services from '@/services/app';
import React from 'react';
import { GIcon, merge, RedirectResponseInterceptor } from 'geminis-react';
import ClientMonitor from 'skywalking-client-js';
import { addRoute, defaultRoutes } from '@/utils/route';
import { avatarRender, defaultLayout } from '@/utils/layout';
import { history } from '@umijs/max';
import { RequestConfig } from '@@/plugin-request/request';
import { loadUser } from '@/utils/currentUser';

const { getLayoutConfig, getRoutesConfig, getMonitorConfig, getMicroAppConfig } = services.AppController;

let routesConfig: Array<App.Route>;

export const request: RequestConfig = {
  responseInterceptors: [[RedirectResponseInterceptor, RedirectResponseInterceptor]],
};

export async function getInitialState() {
  getMonitorConfig()
    .then(config => {
      history.listen(({ location, action }) => {
        if (action === 'POP') {
          ClientMonitor.setPerformance({
            ...config,
            pagePath: location.pathname,
          });
        }
      });
    });

  const currentUser = await loadUser();
  const initialState = {
    layout: merge(defaultLayout, await getLayoutConfig()),
    currentUser,
  };
  localStorage.setItem('IconScriptUrl', JSON.stringify([initialState.layout.iconfontUrl]));
  return initialState;
}

export const layout = ({ initialState }: { initialState: App.InitialState }) => {
  initialState.layout.avatarProps = {
    icon: <GIcon type="icon-user" />,
    title: initialState.currentUser?.name,
    render: avatarRender,
    ...initialState.layout.avatarProps,
  };

  return initialState.layout;
};

export function patchClientRoutes({ routes }: { routes: Array<App.Route> }) {
  if (!routes[0].children) {
    routes[0].children = [];
  }

  defaultRoutes.reverse().forEach(route => {
    routes[0].children.unshift(route);
  });
  addRoute(routes[0], routesConfig);
}

export function render(oldRender: Function) {
  getRoutesConfig()
    .then(routes => {
      routesConfig = routes;
      oldRender();
    });
}

export const qiankun = await getMicroAppConfig();